import { defineStore } from "pinia";
import { getStorage, setStorage } from "@/utils/storage";
import { TAB_KEY } from "@/config/constant";
import router from "@/router";
import type { RouteLocationNormalizedGeneric, RouteRecordRaw } from "vue-router"

export interface MenuState {
    routes: RouteRecordRaw[],
    tabs: RouteLocationNormalizedGeneric[],
    textColor: string
}

export const useMenuStore = defineStore("menu", {
    state: (): MenuState => {
        return {
            routes: [],
            tabs: getStorage(TAB_KEY) || [],
            textColor: "rgb(144, 164, 174)",
        }
    },
    getters: {
        getTabs: (state) => state.tabs
    },
    actions: {
        setRoutes(routes: RouteRecordRaw[]) {
            this.routes = [...routes]
        },
        addTab(route: RouteLocationNormalizedGeneric) {
            if (this.tabs.find(item => item.name == route.name)) {
                return
            }
            this.tabs.push({ ...route })
            setStorage(TAB_KEY, this.tabs)
        },
        removeTab(path: string) {
            this.tabs.map((item, key) => {
                if (item.path == path) {
                    const nextTab = this.tabs[key + 1] || this.tabs[key - 1]
                    this.tabs.splice(key, 1)
                    if (nextTab) {
                        router.replace({ path: nextTab.path })
                    }
                    return
                }
            })
            setStorage(TAB_KEY, this.tabs)
        }
    }
})